设计模式沉思录(七)之 过滤器模式
设计模式目录
过滤器模式(Filter Pattern)
或标准模式(Criteria Pattern)是一种设计模式,这种模式允许开发人员使用不同的标准来过滤一组对象,通过逻辑运算以解耦的方式把它们连接起来。这种类型的设计模式属于结构型模式,它结合多个标准来获得单一标准。
本文整理自四人帮著作:Design Patterns - Elements of Reusable Object-Oriented Software(中文译名:设计模式 - 可复用的面向对象软件元素)
实现
我们将创建一个 Person 对象、Criteria 接口和实现了该接口的实体类,来过滤 Person 对象的列表。CriteriaPatternDemo,我们的演示类使用 Criteria 对象,基于各种标准和它们的结合来过滤 Person 对象的列表。
实现起来很简单。设计过滤器接口,带有过滤方法,能将list对象过滤到一个新的list并返回,多重过滤器实现起来也很简单。在过滤器内部使用单个过滤器多次即可。
步骤 1
创建一个类,在该类上应用标准。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22public class Person {
   
   private String name;
   private String gender;
   private String maritalStatus;
 
   public Person(String name,String gender,String maritalStatus){
      this.name = name;
      this.gender = gender;
      this.maritalStatus = maritalStatus;    
   }
 
   public String getName() {
      return name;
   }
   public String getGender() {
      return gender;
   }
   public String getMaritalStatus() {
      return maritalStatus;
   }  
}
步骤 2
为标准(Criteria)创建一个接口。
1  | import java.util.List;  | 
步骤 3
创建实现了 Criteria 接口的实体类。CriteriaMale
1  | import java.util.ArrayList;  | 
单身狗过滤器1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16import java.util.ArrayList;
import java.util.List;
 
public class CriteriaSingle implements Criteria {
 
   
   public List<Person> meetCriteria(List<Person> persons) {
      List<Person> singlePersons = new ArrayList<Person>(); 
      for (Person person : persons) {
         if(person.getMaritalStatus().equalsIgnoreCase("SINGLE")){
            singlePersons.add(person);
         }
      }
      return singlePersons;
   }
}
组合起来就是~~~~男性单生狗过滤器!!!!!!!1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19AndCriteria.java
import java.util.List;
 
public class AndCriteria implements Criteria {
 
   private Criteria criteria;//过滤器1
   private Criteria otherCriteria;//过滤器2
 
   public AndCriteria(Criteria criteria, Criteria otherCriteria) {
      this.criteria = criteria;
      this.otherCriteria = otherCriteria; 
   }
 
   
   public List<Person> meetCriteria(List<Person> persons) {
      List<Person> firstCriteriaPersons = criteria.meetCriteria(persons);     //过滤器1过滤一遍
      return otherCriteria.meetCriteria(firstCriteriaPersons);//过滤器2过滤一遍
   }
}
最后得到的就是男性单生狗啦。。至于女性,那叫单身贵族。O(∩_∩)O